package com.infojarda.gbasedwiki.web.server.managers;

import javax.jdo.PersistenceManager;

import org.datanucleus.exceptions.NucleusDataStoreException;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.infojarda.gbasedwiki.web.client.services.SettingService;
import com.infojarda.gbasedwiki.web.server.PMF;
import com.infojarda.gbasedwiki.web.server.entities.Setting;


public class SettingManager extends RemoteServiceServlet implements SettingService{

	@Override
	public String readSetting(String settingName) {
		String ret = null;
		Setting setting = findByName(settingName);
		
		return setting.getSettingValue();
	}

	private Setting  findByName(String settingName){
		Setting setting = null;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			setting = pm.getObjectById(Setting.class, settingName);
			
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			pm.close();
		}
		return setting;
	}
	
	@Override
	public void writeStting(String settingName, String settingValue) {
		Setting setting = null;
		setting = findByName(settingName);
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
	
		if(null != setting){
			setting.setSettingValue(settingValue);
			pm.makePersistent(setting);			
		} else {
			setting = new Setting();
			setting.setSettingName(settingName);
			setting.setSettingValue(settingValue);
			pm.makePersistent(setting);
		}
		} finally {
			pm.close();
		}
	}
	
}
